/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.smarttmt.smartmanager.controller;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import org.smarttmt.smartmanager.controller.exceptions.NonexistentEntityException;
import org.smarttmt.smartmanager.controller.exceptions.PreexistingEntityException;
import org.smarttmt.smartmanager.controller.exceptions.RollbackFailureException;
import org.smarttmt.smartmanager.entity.Activida;
import org.smarttmt.smartmanager.entity.Formula;
import org.smarttmt.smartmanager.entity.Estrcheq;

/**
 *
 * @author nicolas
 */
public class ActividaJpaController implements Serializable {

    public ActividaJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Activida activida) throws PreexistingEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Formula actiform = activida.getActiform();
            if (actiform != null) {
                actiform = em.getReference(actiform.getClass(), actiform.getFormcodi());
                activida.setActiform(actiform);
            }
            Estrcheq actilich = activida.getActilich();
            if (actilich != null) {
                actilich = em.getReference(actilich.getClass(), actilich.getEschcodi());
                activida.setActilich(actilich);
            }
            em.persist(activida);
            if (actiform != null) {
                actiform.getActividaList().add(activida);
                actiform = em.merge(actiform);
            }
            if (actilich != null) {
                actilich.getActividaList().add(activida);
                actilich = em.merge(actilich);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findActivida(activida.getActicodi()) != null) {
                throw new PreexistingEntityException("Activida " + activida + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Activida activida) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Activida persistentActivida = em.find(Activida.class, activida.getActicodi());
            Formula actiformOld = persistentActivida.getActiform();
            Formula actiformNew = activida.getActiform();
            Estrcheq actilichOld = persistentActivida.getActilich();
            Estrcheq actilichNew = activida.getActilich();
            if (actiformNew != null) {
                actiformNew = em.getReference(actiformNew.getClass(), actiformNew.getFormcodi());
                activida.setActiform(actiformNew);
            }
            if (actilichNew != null) {
                actilichNew = em.getReference(actilichNew.getClass(), actilichNew.getEschcodi());
                activida.setActilich(actilichNew);
            }
            activida = em.merge(activida);
            if (actiformOld != null && !actiformOld.equals(actiformNew)) {
                actiformOld.getActividaList().remove(activida);
                actiformOld = em.merge(actiformOld);
            }
            if (actiformNew != null && !actiformNew.equals(actiformOld)) {
                actiformNew.getActividaList().add(activida);
                actiformNew = em.merge(actiformNew);
            }
            if (actilichOld != null && !actilichOld.equals(actilichNew)) {
                actilichOld.getActividaList().remove(activida);
                actilichOld = em.merge(actilichOld);
            }
            if (actilichNew != null && !actilichNew.equals(actilichOld)) {
                actilichNew.getActividaList().add(activida);
                actilichNew = em.merge(actilichNew);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = activida.getActicodi();
                if (findActivida(id) == null) {
                    throw new NonexistentEntityException("The activida with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Activida activida;
            try {
                activida = em.getReference(Activida.class, id);
                activida.getActicodi();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The activida with id " + id + " no longer exists.", enfe);
            }
            Formula actiform = activida.getActiform();
            if (actiform != null) {
                actiform.getActividaList().remove(activida);
                actiform = em.merge(actiform);
            }
            Estrcheq actilich = activida.getActilich();
            if (actilich != null) {
                actilich.getActividaList().remove(activida);
                actilich = em.merge(actilich);
            }
            em.remove(activida);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Activida> findActividaEntities() {
        return findActividaEntities(true, -1, -1);
    }

    public List<Activida> findActividaEntities(int maxResults, int firstResult) {
        return findActividaEntities(false, maxResults, firstResult);
    }

    private List<Activida> findActividaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Activida.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Activida findActivida(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Activida.class, id);
        } finally {
            em.close();
        }
    }

    public int getActividaCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Activida> rt = cq.from(Activida.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
